// pages/home/home.js
import { config } from '../../config.js'
import {
  HTTP
} from '../../utils/http-p.js'
const http = new HTTP;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:null,
    authorized:false

  },
  goToLogin:function(){
    wx.navigateTo({ url: '/pages/login/login'})
  },
  goToOrder:function(e){
    if (http.isLogin()) {
      return false
    }
    const active = e.currentTarget.dataset['active'];
    wx.navigateTo({ url: '/pages/order/order?active='+active})
  },
  getUserInfo(){
    wx.getSetting({
      success: data => {
        if (data.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: data => {
              this.setData({
                authorized: true,
                userInfo: data.userInfo
              })
            }
          })
        }else{
          wx.setStorageSync('openId', '')
          this.setData({
            authorized: false,
            userInfo: null
          })
        }
      }
    })
  },

  onGetUserInfo(event) {
    const userInfo = event.detail.userInfo
    if (userInfo) {
      wx.setStorageSync('userInfo', userInfo)
      this.adminLogin()
      this.setData({
        userInfo,
        authorized: true
      })
    } else {
      this.setData({
        authorized: false,
        isLogin: false
      })
    }    
  },
  adminLogin(){
    let than = this
    wx.login({
      success(res) {
        console.log(res)
        if (res.code) {
          //发起网络请求
          wx.request({
            url: config.api_base_url + '/user-info/login',
            data: {
              'code': res.code
            },
            success: (res) => {
              const openId = res.data.openid
              than.addUser(openId)
              wx.setStorageSync('openId', openId)
            }
          })
        } else {
          than.setData({
            authorized: false
          })
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  addUser(openId){
    const data = {
      nickName: this.data.userInfo.nickName,
      avatar: this.data.userInfo.avatarUrl,
      openid: openId
    }
    http.request({
      url: 'user-info/addUser',
      method: 'post',
      data: data,
      success: (res) => {
        
      }
    })

  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})